package com.max.utils;

import com.max.file.FileMetadata;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Maxwell Yu on 4/21/17.
 */
public class ConnectionUtils {

    private static final String ISO8859_1 = "iso8859-1";
    private static final String CHARSET_UTF_8 = "utf-8";

    private static final int HTTP_OK = 200;
    private static final int HTTP_MOVED_TEMP = 302;

    public static synchronized HttpURLConnection getHttpURLConnection(String path) throws IOException {

        //todo add connection pool
        URL url = new URL(path);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        return connection;
    }


    public static FileMetadata getFileMetadata(String fileUrl) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        FileMetadata fileMetadata = null;

        try {
            HttpHead httpHead = new HttpHead(fileUrl);

            ResponseHandler<FileMetadata> responseHandler = response -> {
                switch (response.getStatusLine().getStatusCode()) {
                    case HTTP_OK:
                        return getFileMetaDataFromHead(response);
                    case HTTP_MOVED_TEMP:
                        return getFileMetadata(response.getFirstHeader("location").getValue());
                    default:
                        System.out.println("http code: " + response.getStatusLine().getStatusCode());
                        return null;
                }
            };

            fileMetadata = httpClient.execute(httpHead, responseHandler);
            if (fileMetadata != null) {
                fileMetadata.setLocation(fileUrl);
            }


        } catch (IOException e) {
            System.out.println("con not get file info from headers");
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return fileMetadata;
    }


    private static FileMetadata getFileMetaDataFromHead(HttpResponse response) throws UnsupportedEncodingException {


        FileMetadata fileMetadata = new FileMetadata();

        String fileName = getDownloadFileName(response);
        fileMetadata.setFileName(fileName);


        long fileSize = Long.parseLong(response.getFirstHeader("content-length").getValue());
        fileMetadata.setFileSize(fileSize);
        fileMetadata.setMD5(response.getFirstHeader("content-md5").getValue());

        return fileMetadata;
    }

    private static String getDownloadFileName(HttpResponse response) throws UnsupportedEncodingException {
        String contentDisposition = changeCharSet(response.getFirstHeader("Content-Disposition").getValue());
        return contentDisposition.substring(contentDisposition.indexOf("filename=") + 10,
                contentDisposition.length() - 1);
    }


    private static String changeCharSet(String value) throws UnsupportedEncodingException {
        return new String(value.getBytes(ISO8859_1), CHARSET_UTF_8);

    }
}
